package com.tlgen.config;

import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.PathResource;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.core.io.support.PropertySourceFactory;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.Properties;

import static com.tlgen.constant.Constant.READ_FILE_PATH;

public class YmlPropertySourceFactory implements PropertySourceFactory {

    @Override
    public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
        String sourceName = resource.getResource().getFilename();

        if (!StringUtils.isEmpty(sourceName) && (sourceName.endsWith(".yml") || sourceName.endsWith(".yaml"))) {
            YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
            factory.setResources(resource.getResource());
            factory.afterPropertiesSet();
            Properties properties = factory.getObject();

            return new PropertiesPropertySource(name, properties);
        }
        return null;
    }

    //加载单个配置文件
    public static PropertySource<?> loadProfiles() {
        PathResource resource = new PathResource(READ_FILE_PATH);
        if (!resource.exists()) {
            throw new IllegalArgumentException("资源文件 " + resource + " 不存在");
        }
        try {
            String sourceName = resource.getFilename();
            // 对自定义yml配置文件加载
            YmlPropertySourceFactory ymlResourceFactory = new YmlPropertySourceFactory();
            return ymlResourceFactory.createPropertySource(sourceName, new EncodedResource(resource));
        } catch (IOException ex) {
            throw new IllegalStateException("加载配置文件失败" + resource, ex);
        }
    }

}
